package org.zjx.prop.service;

import org.zjx.prop.domain.model.ItemInstance;
import org.zjx.prop.domain.model.ItemSlot;
import org.zjx.prop.domain.model.ItemTemplate;
import org.zjx.prop.exception.InvalidItemOperationException;
import org.zjx.prop.exception.ItemNotFoundException;
import org.zjx.prop.exception.SlotOperationException;
import org.zjx.prop.repository.ItemSlotRepository;
import org.zjx.prop.repository.ItemTemplateRepository;

import java.util.Optional;

public class ItemValidator {
    private final ItemSlotRepository slotRepository;
    private final ItemTemplateRepository templateRepository;

    public ItemValidator(ItemSlotRepository slotRepository, ItemTemplateRepository templateRepository) {
        this.slotRepository = slotRepository;
        this.templateRepository = templateRepository;
    }

    public void validateMoveOperation(ItemInstance sourceInstance, int targetSlotId) {
        if (sourceInstance == null) {
            throw new ItemNotFoundException("Source item not found");
        }

        Optional<ItemSlot> targetSlotOpt = slotRepository.findById(targetSlotId);
        if (!targetSlotOpt.isPresent()) {
            throw new SlotOperationException("Target slot not found");
        }

        Optional<ItemTemplate> templateOpt = templateRepository.findTemplateById(sourceInstance.getTemplateId());
        if (!templateOpt.isPresent()) {
            throw new ItemNotFoundException("Item template not found");
        }

        if (!targetSlotOpt.get().canInput(templateOpt.get())) {
            throw new InvalidItemOperationException("Item cannot be placed in target slot");
        }
    }
}